import { useState, useEffect } from 'react';
import { Table, Tag, Card, message, Button } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { userAPI } from '@/api/user';

const columns = [
  {
    title: '时间',
    dataIndex: 'createdAt',
    render: text => new Date(text).toLocaleString()
  },
  {
    title: '操作类型',
    dataIndex: 'actionType',
    render: type => <Tag color="processing">{type}</Tag>
  },
  {
    title: '魔力变化',
    dataIndex: 'magicChange',
    render: val => (
        <span style={{ color: val > 0 ? '#52c41a' : '#f5222d', fontWeight: 500 }}>
        {val > 0 ? '+' : ''}{val}
      </span>
    )
  },
  { title: '描述', dataIndex: 'actionDescription' },
  {
    title: '余额',
    dataIndex: 'balanceAfter',
    render: val => <span style={{ fontWeight: 500 }}>{val}</span>
  }
];

export default function MagicLog() {
  const [loading, setLoading] = useState(false);
  const [lastUpdated, setLastUpdated] = useState(null);
  const [data, setData] = useState({
    list: [],
    total: 0,
    pages: 0,
    current: 1
  });

  // 使用状态管理分页
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10
  });

  const loadData = async () => {
    try {
      setLoading(true);

      const res = await userAPI.getMagicLogs({
        page: pagination.current,
        size: pagination.pageSize
      });

      const responseData = res.data.data;

      setData({
        list: responseData.records,
        total: responseData.total,
        pages: responseData.pages,
        current: responseData.current
      });

      // 更新最后刷新时间
      setLastUpdated(new Date());

    } catch (error) {
      message.error('魔力记录加载失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  // 只在分页变化时刷新数据
  useEffect(() => {
    loadData();
  }, [pagination]); // 依赖 pagination 状态

  const handleTableChange = (newPagination) => {
    // 更新分页状态，会触发 useEffect 重新加载数据
    setPagination({
      current: newPagination.current,
      pageSize: newPagination.pageSize
    });
  };

  return (
      <Card
          title={`魔力记录 (最后更新: ${lastUpdated?.toLocaleTimeString() || '--'})`}
          bordered={false}
          extra={
            <Button
                icon={<ReloadOutlined />}
                onClick={loadData} // 手动刷新按钮
                loading={loading}
            >
              刷新
            </Button>
          }
      >
        <Table
            columns={columns}
            rowKey="id"
            dataSource={data.list}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: data.total,
              showSizeChanger: true,
              showTotal: total => `共 ${total} 条记录`,
            }}
            onChange={handleTableChange}
            loading={loading}
        />
      </Card>
  );
}